package linuxbox.admin.taglib;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.*;

import linuxbox.BoxStatic;
import linuxbox.admin.logic.*;
import linuxbox.admin.bean.DeptKey;

/**
 * This class displays a department list.
 */
public class DeptList extends TagSupport {
  protected String listType = null;
  protected int selected = -1;

  public int doStartTag() throws JspException {
    try {
      UserManager um = UserManager.getInstance();
      List ids = um.getAllDepartments();

      JspWriter out = pageContext.getOut();

      Department dept = null;
      DeptKey key = null;

      if ("table".equals(listType)) {
        int length = ids.size();
        for (int i = 0; i < length; i++) {
          if ((i % 2) != 0)
            out.println("<TR bgcolor=\"#E0E0E0\">");
          else
            out.println("<TR>");

          key = (DeptKey)ids.get(i);
          dept = um.getDepartment(key);
          out.println("<TD><A href=\""+BoxStatic.servletDir+"DeptManEditAction?DEPT_ID="
              + dept.getID() + "\">" + dept.getName() + "</A></TD>");
          out.newLine();
          out.println("<TD><a href=\""+BoxStatic.servletDir+"DeptManDelAction?DEPT_ID="
              + dept.getID() + "\">Delete</a></TD>");
          out.newLine();
          out.println("</TR>");out.newLine();
        }
      }

      if ("select".equals(listType)) {
        StringBuffer retVal = new StringBuffer();
        int length = ids.size();
        for (int i = 0; i < length; i++) {
          key = (DeptKey)ids.get(i);
          dept = um.getDepartment(key);

          retVal.append("<OPTION value=" + dept.getID());

          if (dept.getID() == selected) {
            retVal.append(" SELECTED");
          }

          retVal.append(">" + dept.getName() + "</OPTION>");
        }
        out.println(retVal.toString());
      }

      out.flush();
      //out.close();
    } catch(Exception e) {
      BoxStatic.logger.error("Failed to get all users");
      e.printStackTrace();
      throw new JspException(e.getMessage());
    }

    return SKIP_BODY;
  }

  public void setListType(String aValue) {
    listType = aValue;
  }

  public void setSelected(String aValue) {
    selected = Integer.parseInt(aValue);
  }
}
